from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect
import logging

from django.urls import reverse

from oauth.models import OAuthQQUser

logger = logging.getLogger('django')

# Create your views here.
from django.views import View

from meiduo_mall.utils.response_code import RETCODE


class QQURLView(View):
    """
    提供qq登陆网址
    """
    def get(self,request):
        next = request.GET.get('next')

    #     获取qq登陆网址
    #     创建oauthqq类的对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
#     调用对象的获取qq地址方法
        login_url = oauth.get_qq_url()

    # 返回登陆地址
        return http.HttpResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url':login_url})

class QQUserView(View):
    """用户扫码登陆的回调处理"""
    def get(self,request):
        """
        接收code值,判断是否登陆,如果登陆,重定向到首页
        如果未登录,返回access_token
        :param request:
        :return:
        """
    # 1:接收code值
        code = request.GET.get('code')
    # 2:校验参数
        if not code:
            return http.HttpResponseForbidden('缺少必传参数')
    # 3:创建工具类对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                            client_secret=settings.QQ_CLIENT_SECRET,
                            redirect_uri=settings.QQ_REDIRECT_URI)

    # 4:调用工具类方法=====>access_token
        try:
            access_token = oauth.get_access_token(code)
    # 5:调用工具类方法=====>openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
    # 6:如果出错,报错
            logger.error(e)
            return http.HttpResponseServerError('OAuth2.0认证失败')
    # 7:在模型类中根据openid获取用户
        try:
            oauth_qq = OAuthQQUser.objects.get(openid = openid)
        except OAuthQQUser.DoesNotExist:
    # 8:如果没有获取到
            pass
    # 9:如果获取到
        else:
    # 9.1:绑定状态
            user = oauth_qq.user
            login(request,user)
            response = redirect(reverse('contents:index'))
    # 9.2:把cookies写入用户名
            response.set_cookie('username',user,max_age=3600*24*15)
    # 9.3:重定向到元页面
            return response

